package com.kantboot.api.varcode.service.impl;

import com.kantboot.api.email.domain.dto.EmailSendDTO;
import com.kantboot.api.email.domain.entity.ApiEmail;
import com.kantboot.api.email.service.IApiEmailService;
import com.kantboot.api.phone.domain.dto.SmsSendDTO;
import com.kantboot.api.phone.domain.entity.ApiPhoneSms;
import com.kantboot.api.phone.service.IApiPhoneService;
import com.kantboot.api.varcode.domain.dto.ApiVarCodeSearchDTO;
import com.kantboot.api.varcode.domain.entity.ApiVarCode;
import com.kantboot.api.varcode.domain.entity.ApiVarCodeTemplate;
import com.kantboot.api.varcode.domain.dto.ApiVarCodeDTO;
import com.kantboot.api.varcode.exception.ApiVarCodeException;
import com.kantboot.api.varcode.repository.ApiVarCodeRepository;
import com.kantboot.api.varcode.repository.ApiVarCodeTemplateRepository;
import com.kantboot.api.varcode.service.IApiVarCodeService;
import com.kantboot.functional.common.service.ICommonKantbootRsaService;
import com.kantboot.functional.template.domain.dto.FunctionalTemplateGenerateDTO;
import com.kantboot.functional.template.domain.vo.FunctionalTemplateGenerateVO;
import com.kantboot.functional.template.service.IFunctionalTemplateService;
import com.kantboot.util.core.param.PageParam;
import com.kantboot.util.core.result.PageResult;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApiVarCodeServiceImpl implements IApiVarCodeService {

    @Resource
    private ApiVarCodeRepository repository;

    @Resource
    private IApiEmailService emailService;

    @Resource
    private IApiPhoneService phoneService;

    @Resource
    private ApiVarCodeTemplateRepository templateRepository;

    @Resource
    private IFunctionalTemplateService functionalTemplateService;

    @Resource
    private ICommonKantbootRsaService rsaService;

    @Override
    public String generateCode() {
        // 生成6位数字验证码
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append((int) (Math.random() * 10));
        }
        return code.toString();
    }

    @Override
    public void send(ApiVarCodeDTO dto) {
        dto.setValue(generateCode());
        if("email".equals(dto.getTypeCode())){
            sendEmail(dto);
            return;
        }
        if("sms".equals(dto.getTypeCode())){
            sendSms(dto);
            return;
        }
        throw ApiVarCodeException.notSupportTypeCode(dto.getTypeCode());
    }

    @Override
    public void sendSecurity(ApiVarCodeDTO dto) {
        ApiVarCodeDTO dto1 = new ApiVarCodeDTO();
        // 将数据解密
        if(dto.getTypeCode()!=null){
            dto1.setTypeCode(rsaService.decrypt(dto.getTypeCode()));
        }
        if(dto.getSceneCode()!=null){
            dto1.setSceneCode(rsaService.decrypt(dto.getSceneCode()));
        }
        if(dto.getValue()!=null){
            dto1.setValue(rsaService.decrypt(dto.getValue()));
        }
        if(dto.getTo()!=null){
            dto1.setTo(rsaService.decrypt(dto.getTo()));
        }
        if(dto.getTitle()!=null){
            dto1.setTitle(rsaService.decrypt(dto.getTitle()));
        }

        send(dto1);
    }

    @Override
    public void sendEmail(ApiVarCodeDTO dto) {
        // 将类型设置为email
        dto.setTypeCode("email");
        // 将验证码设置为随机生成的6位数字的字符串
        dto.setValue(generateCode());
        ApiVarCode apiVarCode = new ApiVarCode();
        apiVarCode.setTo(dto.getTo());
        apiVarCode.setValue(dto.getValue());
        apiVarCode.setTypeCode(dto.getTypeCode());
        apiVarCode.setSceneCode(dto.getSceneCode());
        // 有效期默认7分钟
        long nowData = System.currentTimeMillis();
        long time = 1000*60*7L;
        apiVarCode.setGmtExpire(new Date(nowData+time));

        // 保存到数据库
        repository.save(apiVarCode);


        ApiVarCodeTemplate byTypeCodeAndSceneCode = templateRepository.findByTypeCodeAndSceneCode(dto.getTypeCode(), dto.getSceneCode());
        if (byTypeCodeAndSceneCode == null) {
            // 提示没有绑定模板
            throw ApiVarCodeException.notBindTemplate(dto.getTypeCode(), dto.getSceneCode());
        }

        FunctionalTemplateGenerateDTO generateDTO = new FunctionalTemplateGenerateDTO();
        generateDTO.setCode(byTypeCodeAndSceneCode.getTemplateCode());
        generateDTO.setGroupCode(byTypeCodeAndSceneCode.getTemplateGroupCode());
        generateDTO.setParams(apiVarCode);
        FunctionalTemplateGenerateVO template = functionalTemplateService.getTemplate(generateDTO);

        EmailSendDTO emailSendDTO = new EmailSendDTO();
        emailSendDTO.setTo(dto.getTo());
        // 将类型设置为verification(验证码类)
        emailSendDTO.setTypeCode(ApiEmail.TYPE_CODE_VERIFICATION);
        emailSendDTO.setSubject(template.getTitle());
        emailSendDTO.setContent(template.getContent());
        emailSendDTO.setIsHtml(true);
        emailService.send(emailSendDTO);
    }

    @Override
    public void sendSms(ApiVarCodeDTO dto) {
        // 将类型设置为email
        dto.setTypeCode("sms");
        // 将验证码设置为随机生成的6位数字的字符串
        dto.setValue(generateCode());
        ApiVarCode apiVarCode = new ApiVarCode();
        apiVarCode.setTo(dto.getTo());
        apiVarCode.setValue(dto.getValue());
        apiVarCode.setTypeCode(dto.getTypeCode());
        apiVarCode.setSceneCode(dto.getSceneCode());
        // 有效期默认7分钟
        long nowData = System.currentTimeMillis();
        long time = 1000*60*7L;
        apiVarCode.setGmtExpire(new Date(nowData+time));
        // 保存到数据库
        repository.save(apiVarCode);
        ApiVarCodeTemplate byTypeCodeAndSceneCode = templateRepository.findByTypeCodeAndSceneCode(dto.getTypeCode(), dto.getSceneCode());
        if (byTypeCodeAndSceneCode == null) {
            // 提示没有绑定模板
            throw ApiVarCodeException.notBindTemplate(dto.getTypeCode(), dto.getSceneCode());
        }

        FunctionalTemplateGenerateDTO generateDTO = new FunctionalTemplateGenerateDTO();
        generateDTO.setCode(byTypeCodeAndSceneCode.getTemplateCode());
        generateDTO.setGroupCode(byTypeCodeAndSceneCode.getTemplateGroupCode());
        generateDTO.setParams(apiVarCode);
        FunctionalTemplateGenerateVO template = functionalTemplateService.getTemplate(generateDTO);
        SmsSendDTO sendDto = new SmsSendDTO();
        sendDto.setTo(dto.getTo());
        sendDto.setContent(template.getContent());
        sendDto.setTypeCode(ApiPhoneSms.TYPE_CODE_VERIFICATION);
        phoneService.send(sendDto);
    }

    @Override
    public Boolean check(ApiVarCodeDTO dto) {
        ApiVarCode valueByTypeCodeAndSceneCodeAndTo = repository.findByTypeCodeAndSceneCodeAndToAndValue(dto.getTypeCode(), dto.getSceneCode(), dto.getTo(), dto.getValue());
        if (valueByTypeCodeAndSceneCodeAndTo == null) {
            return false;
        }
        if (valueByTypeCodeAndSceneCodeAndTo.getGmtExpire().before(new Date())) {
            return false;
        }

        repository.delete(valueByTypeCodeAndSceneCodeAndTo);

        return true;
    }


    @Override
    public PageResult getBodyData(PageParam<ApiVarCodeSearchDTO> pageParam) {
        return PageResult.of(repository.getBodyData(pageParam.getData(),pageParam.getPageable()));
    }
}
